package com.seari.tunnel.controller;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import javax.xml.soap.SOAPException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.seari.tunnel.entity.AlarmHistory;
import com.seari.tunnel.entity.AlarmHistoryPage;
import com.seari.tunnel.entity.OperationHistory;
import com.seari.tunnel.entity.OperationRepair;
import com.seari.tunnel.entity.OperationRepairParam;
import com.seari.tunnel.entity.OperationSpare;
import com.seari.tunnel.entity.OperationSparePage;
import com.seari.tunnel.entity.OperationSpareParam;
import com.seari.tunnel.entity.RecordHistory;
import com.seari.tunnel.entity.job.OPCData;
import com.seari.tunnel.service.IJOBService;
import com.seari.tunnel.service.IOperatMaintenanceService;
import com.seari.tunnel.utils.HCNetSDK;
import com.sun.jna.NativeLong;

@Controller
public class OperationMaintenancController {
	private final String XCXK_PAGE = "/xcxk";
	private final String CZ_PAGE = "/cz";
	private final String FJ_PAGE = "/fj";
	private final String GWDL_PAGE = "/gwdl";
	private final String PSSB_PAGE = "/pssb";
	private final String XFSB_PAGE = "/xfsb";
	private final String SBXK_PAGE = "/sbxk";
	private final String JKGL_PAGE = "/jkgl";
	private final String YHWX_PAGE = "/yhwx";
	private final String BPBJ_PAGE = "/bpbj";
	private final String GDXJ_PAGE = "/gdxj";
	private final String YDXJ_PAGE = "/ydxj";
	private final String KRQT_PAGE = "/krqt";
	private final String WSDY_PAGE = "/wsdy";
	private final String YJ_PAGE = "/yj";
	private final String BYC_PAGE = "/byc";
	
	private static final String ip="192.168.1.106";
	private static final int PORT = 3000;
	static Socket socket;
	static DataInputStream in;
	static DataOutputStream out;
	static byte[] bs = new byte[8];
	
	private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/*NativeLong lUserID = new NativeLong(-1);//用户句柄
	String m_sDeviceIP;//已登录设备的IP地址
	HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo;//设备信息
	static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE;
	NativeLong lRealPlayHandle;*/
	
	private final String SAVE_PATH = "C:/save/";
	
	@Autowired
	IOperatMaintenanceService operatMaintenanceService;
	@Autowired
	IJOBService jobService;
	
	@RequestMapping(value="/jkgl")
	public ModelAndView jkgl(){
		
		return new ModelAndView(JKGL_PAGE);
	}
	
	@RequestMapping(value="/sbxk")
	public ModelAndView sbxk(){
		
		return new ModelAndView(SBXK_PAGE);
	}
	
	@RequestMapping(value="/xcxk")
	public ModelAndView xcxk(){
		
		return new ModelAndView(XCXK_PAGE);
	}
	
	@RequestMapping(value="/cz")
	public ModelAndView cz(){
		
		return new ModelAndView(CZ_PAGE);
	}
	
	@RequestMapping(value="/fj")
	public ModelAndView fj(){
		
		return new ModelAndView(FJ_PAGE);
	}
	
	@RequestMapping(value="/gwdl")
	public ModelAndView gwdl(){
		
		return new ModelAndView(GWDL_PAGE);
	}
	
	@RequestMapping(value="/pssb")
	public ModelAndView pssb(){
		
		return new ModelAndView(PSSB_PAGE);
	}
	
	@RequestMapping(value="/xfsb")
	public ModelAndView xfsb(){
		
		return new ModelAndView(XFSB_PAGE);
	}
	
	@RequestMapping(value="/yhwx")
	public ModelAndView yhwx(){
		
		return new ModelAndView(YHWX_PAGE);
	}
	
	@RequestMapping(value="/bpbj")
	public ModelAndView bpbj(){
		
		return new ModelAndView(BPBJ_PAGE);
	}
	
	@RequestMapping(value="/gdxj")
	public ModelAndView gdxj(){
		
		return new ModelAndView(GDXJ_PAGE);
	}
	
	@RequestMapping(value="/ydxj")
	public ModelAndView ydxj(){
		
		return new ModelAndView(YDXJ_PAGE);
	}
	
	@RequestMapping(value="/krqt")
	public ModelAndView krqt(){
		
		return new ModelAndView(KRQT_PAGE);
	}
	
	@RequestMapping(value="/wsdy")
	public ModelAndView wsdy(){
		
		return new ModelAndView(WSDY_PAGE);
	}
	
	@RequestMapping(value="/yj")
	public ModelAndView yj(){
		
		return new ModelAndView(YJ_PAGE);
	}
	
	@RequestMapping(value="/byc")
	public ModelAndView byc(){
		
		return new ModelAndView(BYC_PAGE);
	}
	
	@RequestMapping(value = "/loadOperationRepairs")
	@ResponseBody
	public Object getOperationRepairGird() {
		List<OperationRepair> data = operatMaintenanceService.findOperationRepairs();
		return data;
	}
	
	@RequestMapping(value="/operatMaintenancEdit")
	@ResponseBody
	public Object operatMaintenancEdit(@ModelAttribute OperationRepairParam operationRepairParam) throws Throwable{
		OperationRepair operationRepair = new OperationRepair();
	        if("add".equals(operationRepairParam.getOper())){
			operationRepair.setRepairNumber(operationRepairParam.getRepairNumber());
			operationRepair.setRepairState(operationRepairParam.getRepairState());
			operationRepair.setDeviceId(operationRepairParam.getDeviceId());
			operationRepair.setApplication(operationRepairParam.getApplication());
		    operationRepair.setApplicationTime(operationRepairParam.getApplicationTime());
		    operationRepair.setStartTime(operationRepairParam.getStartTime());
		    operationRepair.setFinishTime(operationRepairParam.getFinishTime());
		    operationRepair.setStophour(operationRepairParam.getStophour());
		    operationRepair.setRepairLevel(operationRepairParam.getRepairLevel());
		    operationRepair.setRepairPerson(operationRepairParam.getRepairPerson());
		    operationRepair.setRepairCharge(operationRepairParam.getRepairCharge());
		    operationRepair.setRepairFee(operationRepairParam.getRepairFee());
		    operationRepair.setErrorDesc(operationRepairParam.getErrorDesc());
		    operationRepair.setRepairDesc(operationRepairParam.getRepairDesc());
		    operatMaintenanceService.addOperationRepair(operationRepair);
		    
		}
		else if("edit".equals(operationRepairParam.getOper())){
			operationRepair.setId(Integer.parseInt(operationRepairParam.getId()));
			operationRepair.setRepairNumber(operationRepairParam.getRepairNumber());
			operationRepair.setRepairState(operationRepairParam.getRepairState());
			operationRepair.setDeviceId(operationRepairParam.getDeviceId());
			operationRepair.setApplication(operationRepairParam.getApplication());
		    operationRepair.setApplicationTime(operationRepairParam.getApplicationTime());
		    operationRepair.setStartTime(operationRepairParam.getStartTime());
		    operationRepair.setFinishTime(operationRepairParam.getFinishTime());
		    operationRepair.setStophour(operationRepairParam.getStophour());
		    operationRepair.setRepairLevel(operationRepairParam.getRepairLevel());
		    operationRepair.setRepairPerson(operationRepairParam.getRepairPerson());
		    operationRepair.setRepairCharge(operationRepairParam.getRepairCharge());
		    operationRepair.setRepairFee(operationRepairParam.getRepairFee());
		    operationRepair.setErrorDesc(operationRepairParam.getErrorDesc());
		    operationRepair.setRepairDesc(operationRepairParam.getRepairDesc());
		    operatMaintenanceService.updateOperationRepair(operationRepair);
		}
		else{
			operatMaintenanceService.deleteById(Integer.parseInt(operationRepairParam.getId()));
		}
		return operationRepair.getId();
	}
	
	@RequestMapping(value = "/updateOperationRepairFile")
	public  ModelAndView updateOperationRepairFile(@RequestParam("id") int id, @RequestParam("filePath") MultipartFile filePath){
		 String savePath = SAVE_PATH+"operationRepair";
	        File file = new File(savePath);
	        //判断上传文件的保存目录是否存在
	       if (!file.exists() && !file.isDirectory()) {
	            //创建目录
	            file.mkdir();
	       }
	       String fileType = filePath.getContentType();
	       if("application/vnd.openxmlformats-officedocument.wordprocessingml.document".equals(fileType) || "application/msword".equals(fileType) || "application/pdf".equals(fileType) || "image/jpeg".equals(fileType)){
	       String fileName = filePath.getOriginalFilename();
	       try {
	   		InputStream in = filePath.getInputStream();
	   		FileOutputStream out = new FileOutputStream(savePath + "\\" + fileName);
	   		//创建一个缓冲区
	   	    byte buffer[] = new byte[1024];
	   	    //判断输入流中的数据是否已经读完的标识
	   		int len = 0;
	   		 while((len=in.read(buffer))>0){
	   			//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
	   			out.write(buffer, 0, len);
	   			 }
	   			//关闭输入流
	   			in.close();
	   			//关闭输出流
	   			out.close();
	   	} catch (IOException e) {
	   		
	   		e.printStackTrace();
	   	}
	       operatMaintenanceService.updateOperationRepairFile(id, fileName);
	       }
		return new ModelAndView(YHWX_PAGE);
	}
	
	@RequestMapping(value="/operationRepairDownload")
	public void operationRepairDownload(@RequestParam("file") String file,HttpServletRequest req, HttpServletResponse res){
		InputStream is = null;
		OutputStream os = null;
		try {
			res.reset();
			String fileName = new String(file.getBytes("ISO8859-1"),"UTF-8");
			String fName = "";
			if(req.getHeader("User-Agent").toLowerCase().indexOf("firefox")>0){
				fName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
            }else if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE")>0){
            	fName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            }else{
            	fName = URLEncoder.encode(fileName, "UTF-8");
            }
		res.setCharacterEncoding("utf-8");
		if(fileName.contains("doc") || fileName.contains("docx")){
			res.setContentType("application/msword");
		}
        if(fileName.contains("pdf")){
        	res.setContentType("application/pdf");
		}
        if(fileName.contains("jpg")){
        	res.setContentType("image/jpeg");
        }
		res.setHeader("Content-Disposition", "attachment;fileName=\"" + fName + "\"");

            String path = SAVE_PATH+"operationRepair";
            File filePath = new File(path);
            is = new FileInputStream(new File(filePath
                    + File.separator + fileName));
 
            os = res.getOutputStream();
            byte[] mybyte = new byte[8192];
            int len = 0;
            while ((len = is.read(mybyte)) != -1) {
                os.write(mybyte, 0, len);
            }

            os.flush();
             // 这里主要关闭。
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	@RequestMapping(value="/loadOperationSpare")
	@ResponseBody
	public Object loadOperationSpare(@RequestParam("rows")int rows,@RequestParam("page")int page,@RequestParam(value="_search",required=false) boolean search,@RequestParam(value="searchString",required=false) String searchString){
		OperationSparePage pages = new OperationSparePage();
		List<OperationSpare> data= operatMaintenanceService.findOperationSpare();
		int rowCount = 0;
		if(data.size()%rows==0){
			rowCount = data.size()/rows;
		}else{
			rowCount = data.size()/rows+1;
		}
		List<OperationSpare> cdata = new ArrayList<OperationSpare>();
		for(int i=0;i<rows;i++){
			if(i+rows*(page-1)<data.size()){
			cdata.add(data.get(i+rows*(page-1)));
			}
		}
		pages.setPage(page);
		pages.setRecords(data.size());
		pages.setTotal(rowCount);
		pages.setRows(cdata);
		
		if(search==true){
			List<OperationSpare> searchdata=new ArrayList<OperationSpare>();
			try {
				searchString=new String(searchString.getBytes("ISO8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String str[]=searchString.split("&");
			for(int i=0;i<str.length;i++){
				searchdata.clear();
				for(OperationSpare sa:data){
					if(sa.getLocation().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getProviderName().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getSpareCode().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getSpareCount().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getSpareModel().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getSpareName().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(String.valueOf(sa.getSparePrice()).indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(String.valueOf(sa.getSparePriceTotal()).indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getSpareType().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getSpareUnit().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}
				}
				data=new ArrayList<OperationSpare>(searchdata);
			}
			
			return searchdata;
		}
		return pages;
	}
	
	@RequestMapping(value="/operationSpareEdit")
	@ResponseBody
	public ModelAndView operationSpareEdit(@ModelAttribute OperationSpareParam operationSpareParam) throws Throwable{
	    if("add".equals(operationSpareParam.getOper())){
	        OperationSpare operationSpare = new OperationSpare();
		    operationSpare.setSpareCode(operationSpareParam.getSpareCode());
		    operationSpare.setSpareName(operationSpareParam.getSpareName());
		    operationSpare.setSpareModel(operationSpareParam.getSpareModel());
		    operationSpare.setSpareType(operationSpareParam.getSpareType());
		    operationSpare.setSpareCount(operationSpareParam.getSpareCount());
		    operationSpare.setSparePrice(operationSpareParam.getSparePrice());
		    operationSpare.setSparePriceTotal(operationSpareParam.getSparePriceTotal());
		    operationSpare.setSpareUnit(operationSpareParam.getSpareUnit());
		    operationSpare.setProviderName(operationSpareParam.getProviderName());
		    operationSpare.setLocation(operationSpareParam.getLocation());
		    operatMaintenanceService.addOperationSpare(operationSpare);
		}
		else if("edit".equals(operationSpareParam.getOper())){
			OperationSpare operationSpare = new OperationSpare();
	        operationSpare.setId(Integer.parseInt(operationSpareParam.getId()));
		    operationSpare.setSpareCode(operationSpareParam.getSpareCode());
		    operationSpare.setSpareName(operationSpareParam.getSpareName());
		    operationSpare.setSpareModel(operationSpareParam.getSpareModel());
		    operationSpare.setSpareType(operationSpareParam.getSpareType());
		    operationSpare.setSpareCount(operationSpareParam.getSpareCount());
		    operationSpare.setSparePrice(operationSpareParam.getSparePrice());
		    operationSpare.setSparePriceTotal(operationSpareParam.getSparePriceTotal());
		    operationSpare.setSpareUnit(operationSpareParam.getSpareUnit());
		    operationSpare.setProviderName(operationSpareParam.getProviderName());
		    operationSpare.setLocation(operationSpareParam.getLocation());
		    operatMaintenanceService.updateOperationSpare(operationSpare);
		}
		else{
			int id=0;
			if(operationSpareParam.getId().contains(",")){
				id=Integer.parseInt(operationSpareParam.getId().replace(',', ' ').trim());
			}else{
				id=Integer.parseInt(operationSpareParam.getId());
			}
			operatMaintenanceService.deleteOperationSapreById(id);
		}
		return new ModelAndView(BPBJ_PAGE);
	}
	
	@RequestMapping(value = "/xcxk/carback")
	public void carback() {
		try {
		    socket = new Socket(ip,PORT);
			out = new DataOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			in = new DataInputStream(socket.getInputStream());
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x16;
			bs[3]=(byte) 0xff;
			bs[4]=(byte) 0xff;
			bs[5]=(byte) 0xff;
			bs[6]=(byte) 0xff;
			bs[7]=0x68;
			out.write(bs);
			out.flush();
			byte[] rec1 = new byte[8];
			in.read(rec1);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x04;
			bs[7]=0x6c;
			out.write(bs);
			out.flush();
			byte[] rec2 = new byte[8];
			in.read(rec2);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x01;
			bs[7]=0x69;
			out.write(bs);
			out.flush();
			byte[] rec3 = new byte[8];
			in.read(rec3);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x03;
			bs[7]=0x6b;
			out.write(bs);
			out.flush();
			byte[] rec4 = new byte[8];
			in.read(rec4);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x05;
			bs[7]=0x6d;
			out.write(bs);
			out.flush();
			byte[] rec5 = new byte[8];
			in.read(rec5);
			out.close();
			in.close();
			
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value = "/xcxk/carstop")
	public void carstop() {
		try {
			socket = new Socket(ip,PORT);
			out = new DataOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			in = new DataInputStream(socket.getInputStream());
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x16;
			bs[3]=(byte) 0xff;
			bs[4]=(byte) 0xff;
			bs[5]=(byte) 0xff;
			bs[6]=(byte) 0xff;
			bs[7]=0x68;
			out.write(bs);
			out.flush();
			byte[] rec = new byte[8];
			in.read(rec);
			out.close();
			in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value = "/xcxk/cargo")
	public void cargo() {
		try {
			socket = new Socket(ip,PORT);
			out = new DataOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			in = new DataInputStream(socket.getInputStream());
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x16;
			bs[3]=(byte) 0xff;
			bs[4]=(byte) 0xff;
			bs[5]=(byte) 0xff;
			bs[6]=(byte) 0xff;
			bs[7]=0x68;
			out.write(bs);
			out.flush();
			byte[] rec1 = new byte[8];
			in.read(rec1);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x05;
			bs[7]=0x6d;
			out.write(bs);
			out.flush();
			byte[] rec2 = new byte[8];
			in.read(rec2);
			
			out.close();
			in.close();
			
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value = "/carback")
	public void carback1() {
		try {
		    socket = new Socket(ip,PORT);
			out = new DataOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			in = new DataInputStream(socket.getInputStream());
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x16;
			bs[3]=(byte) 0xff;
			bs[4]=(byte) 0xff;
			bs[5]=(byte) 0xff;
			bs[6]=(byte) 0xff;
			bs[7]=0x68;
			out.write(bs);
			out.flush();
			byte[] rec1 = new byte[8];
			in.read(rec1);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x04;
			bs[7]=0x6c;
			out.write(bs);
			out.flush();
			byte[] rec2 = new byte[8];
			in.read(rec2);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x01;
			bs[7]=0x69;
			out.write(bs);
			out.flush();
			byte[] rec3 = new byte[8];
			in.read(rec3);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x03;
			bs[7]=0x6b;
			out.write(bs);
			out.flush();
			byte[] rec4 = new byte[8];
			in.read(rec4);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x05;
			bs[7]=0x6d;
			out.write(bs);
			out.flush();
			byte[] rec5 = new byte[8];
			in.read(rec5);
			out.close();
			in.close();
			
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value = "/carstop")
	public void carstop1() {
		try {
			socket = new Socket(ip,PORT);
			out = new DataOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			in = new DataInputStream(socket.getInputStream());
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x16;
			bs[3]=(byte) 0xff;
			bs[4]=(byte) 0xff;
			bs[5]=(byte) 0xff;
			bs[6]=(byte) 0xff;
			bs[7]=0x68;
			out.write(bs);
			out.flush();
			byte[] rec = new byte[8];
			in.read(rec);
			out.close();
			in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value = "/cargo")
	public void cargo1() {
		try {
			socket = new Socket(ip,PORT);
			out = new DataOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			in = new DataInputStream(socket.getInputStream());
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x16;
			bs[3]=(byte) 0xff;
			bs[4]=(byte) 0xff;
			bs[5]=(byte) 0xff;
			bs[6]=(byte) 0xff;
			bs[7]=0x68;
			out.write(bs);
			out.flush();
			byte[] rec1 = new byte[8];
			in.read(rec1);
			
			bs[0]=0x55;
			bs[1]=0x01;
			bs[2]=0x12;
			bs[3]=0x00;
			bs[4]=0x00;
			bs[5]=0x00;
			bs[6]=0x05;
			bs[7]=0x6d;
			out.write(bs);
			out.flush();
			byte[] rec2 = new byte[8];
			in.read(rec2);
			
			out.close();
			in.close();
			
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value = "/xcxk/doTrackScanning")
	public void doTrackScanning() {
		/*boolean initSuc = hCNetSDK.NET_DVR_Init();
		hCNetSDK.NET_DVR_SetConnectTime(2000, 1);
		hCNetSDK.NET_DVR_SetReconnect(10000, true);
        if (initSuc == true)
        {
		if (lUserID.longValue() > -1)
        {
            //先注销
            hCNetSDK.NET_DVR_Logout_V30(lUserID);
            lUserID = new NativeLong(-1);
        }
		    m_sDeviceIP = "192.168.1.4";//设备ip地址
	        m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30();
	        int iPort = 8000;
	        lUserID = hCNetSDK.NET_DVR_Login_V30(m_sDeviceIP,
	                (short) iPort, "admin", "admin12345678", m_strDeviceInfo);
	        long userID = lUserID.longValue();
	        if (userID == -1)
	        {
	            m_sDeviceIP = "";//登录未成功,IP置为空
	        }else{
	        	
	        	HCNetSDK.NET_DVR_CLIENTINFO struPlayInfo = new HCNetSDK.NET_DVR_CLIENTINFO();
	        	struPlayInfo.lChannel = new NativeLong(1); //预览通道号
	        	lRealPlayHandle =hCNetSDK.NET_DVR_RealPlay_V30(lUserID, struPlayInfo, null, null,true);
	        	hCNetSDK.NET_DVR_PTZCruise(lRealPlayHandle, HCNetSDK.RUN_SEQ, (byte) 1, (byte) 0, (short) 0);
	        	
	        }
	      hCNetSDK.NET_DVR_StopRealPlay(lRealPlayHandle);
	      
	      hCNetSDK.NET_DVR_Logout(lUserID);
	      
	      hCNetSDK.NET_DVR_Cleanup();
	}*/
	}
	
	@RequestMapping(value = "/doTrackScanning")
	public void doTrackScanning1() {
		/*boolean initSuc = hCNetSDK.NET_DVR_Init();
		hCNetSDK.NET_DVR_SetConnectTime(2000, 1);
		hCNetSDK.NET_DVR_SetReconnect(10000, true);
        if (initSuc == true)
        {
		if (lUserID.longValue() > -1)
        {
            //先注销
            hCNetSDK.NET_DVR_Logout_V30(lUserID);
            lUserID = new NativeLong(-1);
        }
		    m_sDeviceIP = "192.168.1.4";//设备ip地址
	        m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30();
	        int iPort = 8000;
	        lUserID = hCNetSDK.NET_DVR_Login_V30(m_sDeviceIP,
	                (short) iPort, "admin", "admin12345678", m_strDeviceInfo);
	        long userID = lUserID.longValue();
	        if (userID == -1)
	        {
	            m_sDeviceIP = "";//登录未成功,IP置为空
	        }else{
	        	
	        	HCNetSDK.NET_DVR_CLIENTINFO struPlayInfo = new HCNetSDK.NET_DVR_CLIENTINFO();
	        	struPlayInfo.lChannel = new NativeLong(1); //预览通道号
	        	lRealPlayHandle =hCNetSDK.NET_DVR_RealPlay_V30(lUserID, struPlayInfo, null, null,true);
	        	hCNetSDK.NET_DVR_PTZCruise(lRealPlayHandle, HCNetSDK.RUN_SEQ, (byte) 1, (byte) 0, (short) 0);
	        	
	        }
	      hCNetSDK.NET_DVR_StopRealPlay(lRealPlayHandle);
	      
	      hCNetSDK.NET_DVR_Logout(lUserID);
	      
	      hCNetSDK.NET_DVR_Cleanup();
	}*/
	}
	
	@RequestMapping(value = "/loadData")
	@ResponseBody
	public Object getData() throws SOAPException, JAXBException, IOException{
		List<OPCData> dataSource = new ArrayList<OPCData>();
		jobService.browse("", dataSource);
		jobService.read(dataSource);
		return dataSource;
	}
	
	@RequestMapping(value = "/updateData")
	public ModelAndView updateData(@RequestParam("str")String str,@RequestParam("n")String n) throws SOAPException, JAXBException, IOException{
		if("baiyechuang".equals(str)){
			if("1".equals(n)){
				str = "DEMO.byc_st";
			}else{
				str="DEMO.byc_sp";
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("百叶窗");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
			n="true";
			jobService.write(str,n);
		}
		if("guang2".equals(str)){
			if("1".equals(n)){
				jobService.write("DEMO.led1_st","true");
				jobService.write("DEMO.led2_st","true");
			}else{
				jobService.write("DEMO.led1_sp","true");
				jobService.write("DEMO.led2_sp","true");
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("灯光");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
		}
		if("guang3".equals(str)){
			//jobService.write("DEMO.led3_st","false");
			//jobService.write("DEMO.led3_sp","false");
			if("1".equals(n)){
				jobService.write("DEMO.led3_st","true");
			}else{
				jobService.write("DEMO.led3_sp","true");
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("应急灯");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
		}
		if("fengji2".equals(str)){
			if("1".equals(n)){
				str = "DEMO.fan_st";
			}else{
				str="DEMO.fan_sp";
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("风机");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
			n="true";
			jobService.write(str,n);
		}
		if("jinggai".equals(str)){
			if("1".equals(n)){
				str = "DEMO.jg_st";
			}else{
				str="DEMO.jg_sp";
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("井盖");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
			n="true";
			jobService.write(str,n);
		}
		if("touliaokou".equals(str)){
			if("1".equals(n)){
				str = "DEMO.tlk_st";
			}else{
				str="DEMO.tlk_sp";
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("投料口");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
			n="true";
			jobService.write(str,n);
		}
		if("shuibeng9".equals(str)){
			if("1".equals(n)){
				str = "DEMO.pump_st";
			}else{
				str="DEMO.pump_sp";
			}
			OperationHistory oh = new OperationHistory();
			oh.setDevice("水泵");
			oh.setValue(n);
			oh.setTime(sdf.format(new Date()));
			operatMaintenanceService.addOperationHistory(oh);
			n="true";
			jobService.write(str,n);
		}
		return new ModelAndView(JKGL_PAGE);
	}
	
	@RequestMapping(value = "/changefjType")
	public void changefjType(@RequestParam("type")String type) throws SOAPException, JAXBException, IOException{
		type=URLDecoder.decode(type, "UTF-8");
		if("手动".equals(type)){
			jobService.write("DEMO.fan_szd","true");
		}else{
			jobService.write("DEMO.fan_szd","false");
		}
		//return new ModelAndView(JKGL_PAGE);
	}
	
	@RequestMapping(value = "/changesbType")
	public void changesbType(@RequestParam("type")String type) throws SOAPException, JAXBException, IOException{
		type=URLDecoder.decode(type, "UTF-8");
		if("手动".equals(type)){
			jobService.write("DEMO.pump_szd","true");
		}else{
			jobService.write("DEMO.pump_szd","false");
		}
			
		//return new ModelAndView(JKGL_PAGE);
	}
	
	@RequestMapping(value="/addAlarmHistory")
	public void addAlarmHistory(@RequestParam("str") String str,@RequestParam("value") String value) throws UnsupportedEncodingException{
		AlarmHistory ah = new AlarmHistory();
		ah.setName(URLDecoder.decode(str, "UTF-8"));
		ah.setValue(value);
		ah.setTime(sdf.format(new Date()));
		operatMaintenanceService.addAlarmHistory(ah);
	}
	
	@RequestMapping(value="/loadAlarmHistory")
	@ResponseBody
	public Object loadAlarmHistory(@RequestParam("rows")int rows,@RequestParam("page")int page){
		AlarmHistoryPage pages = new AlarmHistoryPage();
		List<AlarmHistory> data= operatMaintenanceService.findAlarmHistory();
		int rowCount = 0;
		if(data.size()%rows==0){
			rowCount = data.size()/rows;
		}else{
			rowCount = data.size()/rows+1;
		}
		List<AlarmHistory> cdata = new ArrayList<AlarmHistory>();
		for(int i=0;i<rows;i++){
			if(i+rows*(page-1)<data.size()){
			cdata.add(data.get(i+rows*(page-1)));
			}
		}
		pages.setPage(page);
		pages.setRecords(data.size());
		pages.setTotal(rowCount);
		pages.setRows(cdata);
		return pages;
	}
	
	@RequestMapping(value="/loadHistory")
	@ResponseBody
	public Object loadHistory(@RequestParam("device")String Device,@RequestParam("date")String date){
		OperationHistory oh=new OperationHistory();
		try {
			Device=new String(Device.getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		oh.setDevice(Device);
		oh.setTime(date);
		List<OperationHistory> ohList=operatMaintenanceService.findOperationHistory(oh);
		return ohList;
	}
	
	@RequestMapping(value="/loadDataHistory")
	@ResponseBody
	public Object loadRecordHistory(@RequestParam("device")String Device,@RequestParam("date")String date){
		List<RecordHistory> dhList=null;
		RecordHistory dh=new RecordHistory();
		try {
			Device=new String(Device.getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		dh.setName(Device);
		dh.setTime(date);
		dhList=operatMaintenanceService.findDataHistory(dh);
		return dhList;
	}

	@RequestMapping(value="/loginTwice")
	@ResponseBody
	public Object loginTwice(){
		
		return "123456";
	}
}
